<template>
  <sub-page>
    <main-card>
      <div class="main-table-tools">
        <el-button
          size="small"
          type="primary"
          :loading="isMainRefreshing"
          :disabled="isMainRefreshing"
          @click="triggerMainRefresh"
        >
          刷新列表
        </el-button>
      </div>
      <my-table style="height: auto" class="mytable">
        <el-table :data="tableData" style="width: 100%" header-row-class-name="table-header">
          <el-table-column type="index" label="编号" width="80" align="center" header-align="center" />
          <el-table-column prop="start_time" label="开始时间" min-width="160" align="center" header-align="center" />
          <el-table-column prop="end_time" label="结束时间" min-width="160" align="center" header-align="center" />
          <el-table-column label="游戏时长" min-width="120" align="center" header-align="center">
            <template slot-scope="scope">
              <span>
                {{ scope.row._pointJson && scope.row._pointJson.gameTime ? `${scope.row._pointJson.gameTime} min` : '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="单次价格" min-width="120" align="center" header-align="center">
            <template slot-scope="scope">
              <span>{{ (scope.row._pointJson && scope.row._pointJson.perPrice) || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="奖品信息" min-width="260" align="center" header-align="center">
            <template slot-scope="scope">
              <div
                v-if="scope.row._pointJson && scope.row._pointJson.awardData && scope.row._pointJson.awardData.length"
                class="award-list"
              >
                <div class="award-item" v-for="(aw, idx) in scope.row._pointJson.awardData" :key="idx">
                  <img v-if="aw.prizeImg" :src="aw.prizeImg" width="47" height="31" @error="onPrizeImgError" />
                  <span class="award-name">{{ aw.prizeName || '-' }}</span>
                </div>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="140" align="center" header-align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="openDetail(scope.row)">查看明细</el-button>
            </template>
          </el-table-column>
        </el-table>
      </my-table>

      <div class="pageNation-container">
        <el-pagination
          background
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalResult"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </main-card>

    <!-- 二级弹窗：单局详情列表 -->
    <my-dialog :show="detailDialogVisible">
      <div slot="title" class="dialog-title-row">
        <span class="dialog-title">点数风暴 - 单局详情</span>
        <div class="dialog-tools">
          <el-button
            size="mini"
            type="primary"
            :loading="isRefreshing"
            :disabled="isRefreshing"
            @click="triggerRefresh"
          >
            刷新明细
          </el-button>
          <div class="auto-refresh-switch">
            <span class="switch-label">自动刷新</span>
            <el-switch
              v-model="autoRefreshEnabled"
              active-text="开"
              inactive-text="关"
              @change="onAutoRefreshChange"
            />
          </div>
        </div>
      </div>
      <div class="sum-info">
        <div class="sum-item">
          <div class="label">一共投掷次数</div>
          <div class="value">{{ detailPointInfo.size || 0 }}</div>
        </div>
        <div class="sum-item">
          <div class="label">总消费金额</div>
          <div class="value">{{ detailPointInfo.money || 0 }}</div>
        </div>
      </div>
      <my-table style="height: auto" class="mytable">
        <el-table :data="detailData" style="width: 100%" header-row-class-name="table-header">
          <el-table-column type="index" label="排名" width="80" align="center" header-align="center" />
          <el-table-column label="玩家" min-width="160" header-align="center">
            <template slot-scope="scope">
              <div class="uploadImg">
                <img width="22" height="22" :src="scope.row.avator || scope.row.avatar || defaultAvatar" @error="onAvatarError($event)" />
                <span class="text">{{ scope.row.wx_name || scope.row.nickname || '-' }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="投掷次数" min-width="120" align="center" header-align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.hby_size || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="最高点数" min-width="120" align="center" header-align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.c02 || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="金额" min-width="100" align="center" header-align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.gsum || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="时间" min-width="160" align="center" header-align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.create_time">{{ new Date(scope.row.create_time) | formatDate }}</span>
              <span v-else>-</span>
            </template>
          </el-table-column>

        </el-table>
      </my-table>
      <div class="pageNation-container">
        <el-pagination
          background
          :current-page="detailCurrentPage"
          :page-size="detailPageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="detailTotalResult"
          @current-change="handleDetailCurrentChange"
          @size-change="handleDetailSizeChange"
        />
      </div>
      <div style="text-align: right; padding: 10px 0 20px 0">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </my-dialog>
  </sub-page>
</template>

<script>
import SubPage from '@/components/subPage';
import MainCard from '@/components/mainCard';
import MyTable from '@/components/myTable';
import myDialog from '@/components/myDialog';
import { getPointDiceList, getPointInfo } from '@/api/setting/activityIncome/activityIncomeData';
import { formatDate as formatDateUtil } from '@/utils/format';

export default {
  name: 'pointStormIncome',
  components: { SubPage, MainCard, MyTable, myDialog },
  data() {
    return {
      tableData: [],
      totalResult: 0,
      currentPage: 1,
      pageSize: 10,

      // 详情弹窗
      detailDialogVisible: false,
      selectedDiceId: '',
      detailData: [],
      detailTotalResult: 0,
      detailCurrentPage: 1,
      detailPageSize: 10,
      detailPointInfo: {},

      // 刷新相关状态
      autoRefreshEnabled: false,
      autoRefreshTimer: null,
      isRefreshing: false,
      refreshIntervalMs: 5000,

      // 主表格刷新状态
      isMainRefreshing: false,

      defaultAvatar: require('@/assets/image/icon/userCenter/defaultAvatar.png'),
    };
  },
  computed: {
    liveId() {
      return this.$store.state.liveId;
    },
  },
  created() {
    this.fetchList();
  },
  beforeDestroy() {
    this.stopAutoRefresh();
  },
  watch: {
    detailDialogVisible(newVal) {
      if (newVal) {
        // 弹窗打开时，如果自动刷新已开启，则启动轮询
        if (this.autoRefreshEnabled) {
          this.startAutoRefresh();
        }
      } else {
        // 弹窗关闭时，强制停止轮询
        this.stopAutoRefresh();
      }
    },
    autoRefreshEnabled(newVal) {
      if (newVal) {
        // 开启自动刷新时，如果弹窗可见则启动轮询
        if (this.detailDialogVisible) {
          this.startAutoRefresh();
        }
      } else {
        // 关闭自动刷新时，停止轮询
        this.stopAutoRefresh();
      }
    },
  },
  methods: {
    onAvatarError(e) {
      e.target.src = this.defaultAvatar;
    },
    onPrizeImgError(e) {
      // 隐藏错误图片，避免破图
      e.target.style.display = 'none';
    },
    getField(row, keys) {
      if (!row || !Array.isArray(keys)) return '-';
      for (let i = 0; i < keys.length; i += 1) {
        const k = keys[i];
        const val = row[k];
        if (val !== undefined && val !== null && val !== '') return val;
      }
      return '-';
    },
    // 一级分页
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchList();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.fetchList();
    },
    // 二级分页
    handleDetailCurrentChange(page) {
      this.detailCurrentPage = page;
      this.fetchDetailList();
    },
    handleDetailSizeChange(size) {
      this.detailPageSize = size;
      this.detailCurrentPage = 1;
      this.fetchDetailList();
    },
    // 获取第一层列表
    fetchList() {
      if (this.isMainRefreshing) {
        return Promise.resolve();
      }

      this.isMainRefreshing = true;
      const params = {
        splid: this.liveId,
        currentPage: `${this.currentPage}`,
        showCount: `${this.pageSize}`,
      };

      return getPointDiceList(params)
        .then((res) => {
          const data = res.data || {};
          const list = (data.list || []).map((item) => {
            let pObj = null;
            if (item && item.pointJson) {
              try {
                pObj = typeof item.pointJson === 'string' ? JSON.parse(item.pointJson) : item.pointJson;
              } catch (e) {
                pObj = null;
              }
            }
            return { ...item, _pointJson: pObj };
          });
          this.tableData = list;
          this.totalResult = data.totalResult || 0;
        })
        .catch(() => {
          this.tableData = [];
          this.totalResult = 0;
        })
        .finally(() => {
          this.isMainRefreshing = false;
        });
    },
    // 主动刷新主列表
    triggerMainRefresh() {
      this.fetchList();
    },
    // 打开详情弹窗
    openDetail(row) {
      this.selectedDiceId = row.dice_id || '';
      this.detailDialogVisible = true;
      this.detailCurrentPage = 1;
      this.fetchDetailList();
    },
    // 获取第二层列表
    fetchDetailList() {
      if (this.isRefreshing) {
        return Promise.resolve();
      }

      this.isRefreshing = true;
      const params = {
        splid: this.liveId,
        dice_id: this.selectedDiceId,
        currentPage: `${this.detailCurrentPage}`,
        showCount: `${this.detailPageSize}`,
      };

      return getPointInfo(params)
        .then((res) => {
          const data = res.data || {};
          this.detailData = data.list || [];
          this.detailTotalResult = data.totalResult || 0;
          this.detailPointInfo = data.pointInfo || {};
        })
        .catch(() => {
          this.detailData = [];
          this.detailTotalResult = 0;
        })
        .finally(() => {
          this.isRefreshing = false;
        });
    },
    // 主动刷新
    triggerRefresh() {
      if (!this.detailDialogVisible || this.isRefreshing) {
        return;
      }
      this.fetchDetailList();
    },
    // 开始自动刷新
    startAutoRefresh() {
      if (this.autoRefreshTimer) {
        return;
      }

      this.autoRefreshTimer = setInterval(() => {
        if (this.detailDialogVisible && !this.isRefreshing) {
          this.fetchDetailList();
        }
      }, this.refreshIntervalMs);
    },
    // 停止自动刷新
    stopAutoRefresh() {
      if (this.autoRefreshTimer) {
        clearInterval(this.autoRefreshTimer);
        this.autoRefreshTimer = null;
      }
    },
    // 自动刷新开关变化
    onAutoRefreshChange(enabled) {
      if (enabled) {
        this.startAutoRefresh();
      } else {
        this.stopAutoRefresh();
      }
    },
  },
  filters: {
    // 时间戳
    formatDate(time) {
      if (!time) return '-';
      const date = time instanceof Date ? time : new Date(time);
      return formatDateUtil(date, 'yyyy/MM/dd hh:mm:ss');
    },
  },
};
</script>

<style lang="less" scoped>
.mytable {
  .uploadImg {
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      border-radius: 50%;
      margin-right: 5px;
      vertical-align: middle;
    }
  }
  .text {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
.award-list {
  display: inline-flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 8px 16px;
}
.award-item {
  display: inline-flex;
  align-items: center;
}
.award-item img {
  border-radius: 4px;
  margin-right: 6px;
}
.award-name {
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.pageNation-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}
.dialog-title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.dialog-title {
  font-size: 18px;
  font-weight: 600;
}
.dialog-tools {
  display: flex;
  align-items: center;
  gap: 12px;
}
.auto-refresh-switch {
  display: flex;
  align-items: center;
  gap: 8px;
}
.switch-label {
  font-size: 14px;
  color: #606266;
}
.main-table-tools {
  display: flex;
  align-items: center;
  padding-top: 20px;
  padding-left: 40px;
}
.sum-info {
  display: flex;
  gap: 24px;
  padding: 10px 0;
}
.sum-item {
  display: flex;
  flex-direction: column;
}
.sum-item .label {
  font-size: 12px;
  color: #666666;
}
.sum-item .value {
  font-size: 18px;
  color: #fb466c;
}
</style>
